package thread.synchroCode;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class _10PrintFiveTimesByLock {
  public static void main(String[] args) {
    AwaitSignal awaitSignal = new AwaitSignal(5);
    Condition a = awaitSignal.newCondition();
    Condition b = awaitSignal.newCondition();
    Condition c = awaitSignal.newCondition();
    new Thread(() -> {
      awaitSignal.print("a", a, b);
    }).start();
    new Thread(() -> {
      awaitSignal.print("b", b, c);
    }).start();
    new Thread(() -> {
      awaitSignal.print("c", c, a);
    }).start();

    try {
      Thread.sleep(1000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    awaitSignal.lock();
    try {
      System.out.println("开始...");
      a.signal();
    } finally {
      awaitSignal.unlock();
    }
  }

  @Slf4j(topic = "asdfasdfasdf")
  static class AwaitSignal extends ReentrantLock{
    private int loopNumber;

    public AwaitSignal(int loopNumber) {
      this.loopNumber = loopNumber;
    }
    //            参数1 打印内容， 参数2 进入哪一间休息室, 参数3 下一间休息室
    public void print(String str, Condition current, Condition next) {
      for (int i = 0; i < loopNumber; i++) {
        lock();
        try {
          current.await();
          log.debug(str);
          next.signal();
        } catch (InterruptedException e) {
          e.printStackTrace();
        } finally {
          unlock();
        }
      }
    }
  }
}
